package com.chenailin.www.service;

import com.chenailin.www.dao.DepartmentDAO;
import com.chenailin.www.dao.DoctorDAO;
import com.chenailin.www.dao.RatingDAO;
import com.chenailin.www.daoimpl.DepartmentDAOImpl;
import com.chenailin.www.daoimpl.DoctorDAOImpl;
import com.chenailin.www.daoimpl.RatingDAOImpl;
import com.chenailin.www.exception.ServiceException;
import com.chenailin.www.pojo.Rating;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class RatingService {
    private final RatingDAO ratingDAO = new RatingDAOImpl();
    private final DoctorDAO doctorDAO = new DoctorDAOImpl();
    private final DepartmentDAO departmentDAO = new DepartmentDAOImpl();

    // 添加评价
    public boolean addRating(Rating rating) {
        // 验证评分范围
        if (rating.getServiceQuality() < 1 || rating.getServiceQuality() > 5 ||
                rating.getEnvironment() < 1 || rating.getEnvironment() > 5) {
            throw new IllegalArgumentException("评分必须在1-5分之间");
        }

        // 限制评价长度
        if (rating.getComment() != null && rating.getComment().length() > 500) {
            throw new IllegalArgumentException("评价内容不能超过500字");
        }

        try {
            return ratingDAO.addRating(rating);
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("添加评价失败", e);
        }
    }

    // 查询医生所有评价
    public List<Rating> getDoctorRating(int doctorId) {
        if (doctorDAO.findById(doctorId) == null) {
            System.out.println("无效医生id！");
            return null;
        }

        return ratingDAO.getRatingsByDoctor(doctorId);
    }

    // 查询科室所有评价
    public List<Rating> getRatingsByDepartment(int departmentId) {
        if (departmentDAO.findById(departmentId) == null) {
            System.out.println("无效科室id！");
            return null;
        }

        return ratingDAO.getRatingsByDepartment(departmentId);
    }

    // 计算医生评分 ???
    public double calculateDoctorRating(int doctorId) {
        return ratingDAO.getAverageRatingByDoctor(doctorId);
    }

    // 计算科室评分
    public double calculateDepartmentRating(int departmentId) {
        return ratingDAO.getAverageDepartmentRating(departmentId);
    }
}
